﻿using MeterialManager.Aop.ExceptionProcess;
using MeterialManager.Utility;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using System.Windows.Forms;

namespace MeterialManager.Aop.ServiceProcess
{
    public class ServiceProxy<T> : DispatchProxy
    {
        private T _target;

        public static T Create(T target)
        {
            //object proxy = Create(typeof(ServiceProxy), target, new[] { typeof(T) });
            var proxy = Create<T, ServiceProxy<T>>();
            (proxy as ServiceProxy<T>)._target = target;
            return proxy;
        }

        protected override object Invoke(MethodInfo targetMethod, object[] args)
        {
            object result = null;
            var transactionAttribute = targetMethod.GetCustomAttribute<TransactionAttribute>();

            if (transactionAttribute != null)
            {
                using (var transactionScope = new TransactionScope())
                {
                    try
                    {
                        result = targetMethod.Invoke(_target, args);
                        ResponseObject<int> responseObject = (ResponseObject<int>)result;
                        if (responseObject.code != 200)
                        {
                            throw new SqlProcessException(responseObject.code, responseObject.msg);
                        }
                        transactionScope.Complete();
                    }
                    catch
                    {
                        // Handle exception
                        return result;
                    }
                }
            }
            else
            {
                result = targetMethod.Invoke(_target, args);
            }

            return result;
        }
    }



}
